import matplotlib.pyplot as plt
import numpy as np
motorbike = plt.imread('motorbike.png')
# or
#motorbike = plt.imread('motorbike.png')[:,:,0]
motorbike[0,0]
array([0.88235295, 0.88235295, 0.88235295], dtype=float32)
plt.imshow(motorbike)
<matplotlib.image.AxesImage at 0x2604844c3a0>
motorbike.shape
(552, 640, 3)
motorbike[0,0]
array([0.88235295, 0.88235295, 0.88235295], dtype=float32)
Note: the image itself is a grayscale image (meaning the red-values, green-values, and blue-values are equal for each pixel). On the other hand, plt.imread() loaded the image with full RGB values (i.e. there is a third dimension of length 3).
motorbike_gray = motorbike[:,:,0] # Take just the red-values for our grayscale value
motorbike_gray.shape
(552, 640)
motorbike_gray[0,0]
0.88235295
plt.imshow(motorbike_gray)
<matplotlib.image.AxesImage at 0x260484aab20>
plt.imshow(motorbike_gray, cmap='gray') # Tell imshow to use a gray colormap
<matplotlib.image.AxesImage at 0x26048688460>
Recall from last week: Use np.random.rand to generate salt and pepper noise:
nrows,ncols = motorbike_gray.shape
pepper_mask = np.random.rand(nrows,ncols) < .05
motorbike_noise = motorbike_gray.copy()
motorbike_noise[pepper_mask] = 0
salt_mask = np.random.rand(nrows,ncols) < .05
motorbike_noise[salt_mask] = 1
plt.figure(figsize=(15,15))
plt.imshow(motorbike_noise, cmap = 'gray')
<matplotlib.image.AxesImage at 0x26049523340>
# This code would give approximately 10% image noise
# 5% from salt noise
# 5% from pepper noise
motorbike_noise = motorbike_gray.copy()
nrows,ncols = motorbike_noise.shape
pepper_mask = np.random.rand(nrows,ncols) < .05
salt_mask = np.random.rand(nrows,ncols) < .05
motorbike_noise[pepper_mask] = 0
motorbike_noise[salt_mask] = 1
plt.figure(figsize=(15,15))
plt.imshow(motorbike_noise,cmap='gray')
<matplotlib.image.AxesImage at 0x2604aeea6a0>
The above code is biased toward salt noise, since we set salt noise second. In other words, we might change previously pepper noised pixels to salt noised pixels.
# This code would give approximately 10% image noise
# 5% from salt noise
# 5% from pepper noise
motorbike_noise = motorbike_gray.copy()
nrows,ncols = motorbike_noise.shape
random_array = np.random.rand(nrows, ncols)
pepper_mask = random_array < .05
salt_mask = random_array > .95
motorbike_noise[pepper_mask] = 0
motorbike_noise[salt_mask] = 1
plt.figure(figsize=(15,15))
plt.imshow(motorbike_noise,cmap='gray')
<matplotlib.image.AxesImage at 0x2604b128970>
def sp_noise(img, noise):
...
return img_noise
filtered_img = np.zeros_like(img)
for i in range(1,nrows-1):
for j in range(1,ncols-1):
...
filtered_img[i,j] =
monkey = plt.imread('monkey.jpg')
plt.imshow(monkey)
<matplotlib.image.AxesImage at 0x2604cad3cd0>
monkey_gray = np.mean(monkey,axis=2)
plt.imshow(monkey_gray,cmap = 'gray')
<matplotlib.image.AxesImage at 0x2604c9baf10>